/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import 'package:example/utils.dart';
import 'package:flutter/material.dart';
import 'package:hadss_adaptive_video/hadss_adaptive_video.dart';
import 'package:video_player/video_player.dart';

class FullScreenVideoPage extends StatefulWidget {
  final VideoPlayerController videoController;

  const FullScreenVideoPage({Key? key, required this.videoController})
      : super(key: key);

  @override
  State<FullScreenVideoPage> createState() => _FullScreenVideoPageState();
}

class _FullScreenVideoPageState extends State<FullScreenVideoPage>
    with WidgetsBindingObserver {
  Duration _currentPosition = Duration.zero;
  bool _isDragging = false;
  Size _windowSize = Size.zero;
  late ScreenRotationCallback _rotationListener;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _rotationListener = (Orientation orientation) {
      if (FullScreenPlayUtils.isFullScreen &&
          orientation == Orientation.portrait) {
        _exitFullScreen();
      }
    };
    AdaptiveRotation().addRotationListener(_rotationListener);
    widget.videoController.addListener(_videoListener);
    widget.videoController.play();
    widget.videoController.setLooping(true);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      AdaptiveRotation().setFullScreen(
          videoSize: widget.videoController.value.size,
          screenSize: MediaQuery.of(context).size);
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // 窗口大小变化
    final logicalSize = MediaQuery.of(context).size;
    if (FullScreenPlayUtils.isFullScreen && _windowSize != logicalSize) {
      _windowSize = logicalSize;
      AdaptiveRotation().setFullScreen(
          videoSize: widget.videoController.value.size,
          screenSize: _windowSize);
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: _buildContent(),
        onWillPop: () async {
          return false; // 禁止返回
        });
  }

  Widget _buildContent() {
    return Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
            top: false,
            bottom: false,
            child: GestureDetector(
              onTap: () {},
              child: Stack(
                children: [
                  Center(
                    child: AspectRatio(
                      aspectRatio: widget.videoController.value.aspectRatio,
                      child: VideoPlayer(widget.videoController),
                    ),
                  ),
                  Column(
                    children: [
                      AppBar(
                        backgroundColor: Colors.transparent,
                        elevation: 0,
                        leading: IconButton(
                          icon:
                              const Icon(Icons.arrow_back, color: Colors.white),
                          onPressed: () {
                            // 退出全屏
                            _exitFullScreen();
                          },
                        ),
                        title: const Text(
                          '视频播放',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      // 播放控制区
                      Expanded(child: Container()),
                      Slider(
                        value: _currentPosition.inSeconds.toDouble(),
                        min: 0,
                        max: widget.videoController.value.duration.inSeconds
                            .toDouble(),
                        onChangeStart: (_) => _isDragging = true,
                        onChangeEnd: (value) {
                          widget.videoController
                              .seekTo(Duration(seconds: value.toInt()));
                          _isDragging = false;
                        },
                        onChanged: (value) {
                          setState(() {
                            _currentPosition = Duration(seconds: value.toInt());
                          });
                        },
                        activeColor: Colors.red,
                      ),
                    ],
                  )
                ],
              ),
            )));
  }

  void _videoListener() {
    if (!_isDragging && mounted) {
      setState(() {
        _currentPosition = widget.videoController.value.position;
      });
    }
  }

  void _exitFullScreen() {
    // 退出全屏时，注销避免窗口旋转再次触发
    if (mounted) {
      widget.videoController.removeListener(_videoListener);
      WidgetsBinding.instance.removeObserver(this);
      AdaptiveRotation().removeRotationListener(_rotationListener);
      FullScreenPlayUtils.exitFullScreen(context);
    }
  }
}
